/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * VentanaAjedrez.java
 *
 * Created on 26-may-2010, 15:03:10
 */
package Main;

import Herramientas.Conversor;
import Ajedrez.*;

import Herramientas.Tarea;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

/**
 *
 * @author Carlos
 */
public class VentanaAjedrez extends javax.swing.JFrame implements ActionListener{

    Ajedrez aj;
    boolean conectado = false;
    boolean jugando = false;
    String iniTextArea = "Inicio de Partida:\n";
    private static final String piezas[] = {"rey", "reina", "torre", "alfil", "caballo", "peon", "Nrey", "Nreina", "Ntorre", "Nalfil", "Ncaballo", "Npeon", "blanco"};
    private ArrayList<String> movimientos = new ArrayList<String>();

    /** Creates new form VentanaAjedrez */
    public VentanaAjedrez(Ajedrez aj) throws IOException {
        initComponents();
        this.setTitle("Ajedrez");
        ImageIcon torr = new ImageIcon("torre1.gif");
        this.setIconImage(torr.getImage());
        jTextArea1.setText(iniTextArea);

        this.aj = aj;
        initAjedrez();
        this.setSize(1000, 570);
        this.setResizable(false);
        this.jPanel2.setMaximumSize(this.jPanel2.getSize());
        this.jPanel2.setMinimumSize(this.jPanel2.getSize());
        //aj.requestFocus();
        aj.setFocusable(false);
    }


    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jDialogServidor = new javax.swing.JDialog();
        jLabel2 = new javax.swing.JLabel();
        jTextDireccionIP = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jTextPuerto = new javax.swing.JTextField();
        aceptarServidor = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jLabelTurno = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextAreaTareas = new javax.swing.JTextArea();
        botonJugar = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenuArchivo = new javax.swing.JMenu();
        jMenuSalir = new javax.swing.JMenuItem();

        jDialogServidor.setTitle("Dirección del Servidor");
        jDialogServidor.setResizable(false);

        jLabel2.setText("Dirección IP del Servidor");

        jTextDireccionIP.setText("192.168.88.129");

        jLabel4.setText("Puerto");

        jTextPuerto.setText("6000");
        jTextPuerto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextPuertoActionPerformed(evt);
            }
        });

        aceptarServidor.setText("Aceptar");
        aceptarServidor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                aceptarServidorActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jDialogServidorLayout = new javax.swing.GroupLayout(jDialogServidor.getContentPane());
        jDialogServidor.getContentPane().setLayout(jDialogServidorLayout);
        jDialogServidorLayout.setHorizontalGroup(
            jDialogServidorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jDialogServidorLayout.createSequentialGroup()
                .addGroup(jDialogServidorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jDialogServidorLayout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jDialogServidorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jTextDireccionIP)
                            .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel4)
                            .addComponent(jTextPuerto)))
                    .addGroup(jDialogServidorLayout.createSequentialGroup()
                        .addGap(29, 29, 29)
                        .addComponent(aceptarServidor)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jDialogServidorLayout.setVerticalGroup(
            jDialogServidorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jDialogServidorLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextDireccionIP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextPuerto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 38, Short.MAX_VALUE)
                .addComponent(aceptarServidor)
                .addContainerGap())
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                formKeyReleased(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        jLabel3.setText("Movimientos Realizados");

        jTextArea1.setColumns(20);
        jTextArea1.setEditable(false);
        jTextArea1.setRows(5);
        jTextArea1.setText("Inicio de Partida:\n");
        jScrollPane1.setViewportView(jTextArea1);

        jLabelTurno.setText("Blancas");

        jLabel1.setText("Turno: ");

        jLabel5.setText("Info:");

        jTextAreaTareas.setColumns(20);
        jTextAreaTareas.setEditable(false);
        jTextAreaTareas.setRows(5);
        jScrollPane2.setViewportView(jTextAreaTareas);

        botonJugar.setText("¡JUGAR!");
        botonJugar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonJugarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 344, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 344, Short.MAX_VALUE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(jLabelTurno, javax.swing.GroupLayout.DEFAULT_SIZE, 66, Short.MAX_VALUE)
                        .addGap(152, 152, 152)
                        .addComponent(botonJugar)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 209, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabelTurno)
                    .addComponent(botonJugar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel3.setMaximumSize(new java.awt.Dimension(550, 550));
        jPanel3.setMinimumSize(new java.awt.Dimension(500, 500));
        jPanel3.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jPanel3MouseClicked(evt);
            }
        });
        jPanel3.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                jPanel3MouseMoved(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 500, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 510, Short.MAX_VALUE)
        );

        jMenuArchivo.setLabel("Archivo");

        jMenuSalir.setText("Salir");
        jMenuSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuSalirActionPerformed(evt);
            }
        });
        jMenuArchivo.add(jMenuSalir);

        jMenuBar1.add(jMenuArchivo);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jPanel3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel3MouseClicked
    }//GEN-LAST:event_jPanel3MouseClicked

    private void jPanel3MouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel3MouseMoved
    }//GEN-LAST:event_jPanel3MouseMoved

    private void aceptarServidorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aceptarServidorActionPerformed
    
    }//GEN-LAST:event_aceptarServidorActionPerformed

    private void jTextPuertoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextPuertoActionPerformed
    }//GEN-LAST:event_jTextPuertoActionPerformed

private void jMenuSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuSalirActionPerformed
    this.windowClosing(null);
}//GEN-LAST:event_jMenuSalirActionPerformed

private void formKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyReleased

}//GEN-LAST:event_formKeyReleased

    private void botonJugarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonJugarActionPerformed
        // TODO add your handling code here:
        this.jugando = true;
        this.botonJugar.setEnabled(false);
        this.aj.nuevaPartida();
        // Lanzar los assert a prolog y el play
    }//GEN-LAST:event_botonJugarActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton aceptarServidor;
    private javax.swing.JButton botonJugar;
    private javax.swing.JDialog jDialogServidor;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabelTurno;
    private javax.swing.JMenu jMenuArchivo;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuSalir;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextArea jTextAreaTareas;
    private javax.swing.JTextField jTextDireccionIP;
    private javax.swing.JTextField jTextPuerto;
    // End of variables declaration//GEN-END:variables


    public void windowClosing(java.awt.event.ActionEvent evt){
        System.exit(0);
    }


    public void resetTextArea(){
        this.jTextArea1.setText(this.iniTextArea);        
    }
    
    /*
     Cambia el área donde se muestra el desarrollo de la partida.
     */
    public void cambiarTextArea(String s) {
        movimientos.add(s);
        pintarTextArea();
        aj.flag = false;
    }
    
    private void pintarTextArea(){
        jTextArea1.setText("");
        int numMov = 0
                ,i = 0;
        for(String mov : movimientos){
            if(i%2 == 0){
                jLabelTurno.setText("Negras");
                numMov++;
                jTextArea1.append(numMov + ". " + mov + "\t");
            }
            else{
                jLabelTurno.setText("Blancas");
                mov = "... " + mov;
                jTextArea1.append(mov + "\n");
            }
            i++;
        }
    }

    /*
     Inicializa el ajedrez y prepara el panel donde va a ir el tablero.
     */
    private void initAjedrez() {
        aj.setLayout(new GridLayout(10, 10));
        aj.setVisible(true);
        aj.setSize(500, 500);

        // setResizable(false);
        int posX = 0;
        int posY = 0;

        ponerAccionBotones();
        aj.setJugador(Ajedrez.blancas);
        for (posX = 0; posX < 10; posX++) {
            for (posY = 0; posY < 10; posY++) {
                if (posX == 0 || posX == 9) {
                    JPanel j = new JPanel();
                    j.setBackground(Color.lightGray);
                    if (posY != 0 && posY != 9) {
                        JLabel l = new JLabel(Conversor.letra(posY - 1));
                        j.add(l);
                    }
                    aj.add(j);

                } else if (posY == 0 || posY == 9) {
                    JPanel j = new JPanel();
                    JLabel l = new JLabel((9 - posX) + "");
                    j.add(l);
                    j.setBackground(Color.lightGray);
                    aj.add(j);
                    
                } else {
                    aj.add(aj.ficha[posX-1][posY-1]);
                }
            }
        }
        aj.repintarImagenes();
        jPanel3.add(this.aj);
        jTextArea1.setText(iniTextArea);
        jLabelTurno.setText("Blancas");
    }

    /*
     La acción que se realiza cada vez que se pinche en una casilla del tablero
     */
    private void accionGeneralBotones(Posicion p){
        String s = aj.Turno(p);
        if(this.aj.getJugador() == Ajedrez.blancas){
            // Se consulta el movimiento que debe realizar las blancas
            String consulta = s + ".";
            if(!aj.enviarMovimientoAProlog(consulta)){ // El movimiento del usuario no es válido
                aj.deshacerMovimiento();
                movimientos.remove(movimientos.size()-1);
                pintarTextArea();
                aj.informar(Tarea.MOVIMIENTO_INVALIDO);
            }
            else // El movimiento del usuario es válido
                aj.consultarMovimientoAProlog();
        }
    }
    
    /*
     La acción que se realiza cada vez que se pinche en una casilla del tablero mientras se colocan las piezas
     */
    private void accionPonerPiezas(BotonCasilla bc){
        String aux = (String) JOptionPane.showInputDialog(null, "Selecciona la pieza de esta casilla", "Seleccion", JOptionPane.QUESTION_MESSAGE, null, piezas, piezas[0]);
        aj.fichaInicial[bc.getPosX()][bc.getPosY()] = aux;
        bc.setPieza(aux);
        aj.repintarImagenes();
    }

    /*
     Añade el listener a los botones
     */
    private void ponerAccionBotones() {
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                aj.ficha[i][j] = new BotonCasilla(i,j);
                aj.ficha[i][j].addActionListener(this);
            }
        }
    }
    
    public void informarDeTarea(String tarea){
        this.jTextAreaTareas.append(tarea+"\n");
        this.jTextAreaTareas.setCaretPosition(this.jTextAreaTareas.getText().length());
    }
    
    @Override
    public void actionPerformed(ActionEvent e) {
        BotonCasilla fuente = (BotonCasilla)e.getSource();
        if(jugando)
            accionGeneralBotones( new Posicion(fuente.getPosX(), fuente.getPosY()) );
        else
            accionPonerPiezas(fuente);
    }
    
}
